package com.qianyitian.hope2.spider.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qianyitian.hope2.sdk.funds.FundInfo;
import com.qianyitian.hope2.spider.config.PropertyConfig;
import com.qianyitian.hope2.spider.external.XiaoXiongClient;
import com.qianyitian.hope2.spider.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DataService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    PropertyConfig propertyConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private XiaoXiongClient xiaoXiongClient;





    private List<FundInfo> getFundNames() {
        Set<String> types = new HashSet();
        List<FundInfo> list = new LinkedList();
        String fundNames = xiaoXiongClient.getFundNames(propertyConfig.getXiaoxiongToken());
        JSONObject jsonObject = JSON.parseObject(fundNames);
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONArray item = data.getJSONArray(i);
            String code = item.getString(0);
            String name = item.getString(2);
            String type = item.getString(3);
            types.add(type);
            FundInfo fund = new FundInfo();
            fund.setName(name);
            fund.setCode(code);
            fund.setType(type);
            list.add(fund);
        }

        Map<String, List<FundInfo>> collect = list.stream().filter(item -> {
            String type = item.getType();
            return (type.equals("混合型-灵活") || type.equals("混合-绝对收益") || type.equals("混合-绝对收益") || type.equals("混合型-偏股")
                    || type.equals("股票型") || type.equals("混合型-平衡"));

        }).collect(Collectors.groupingBy(FundInfo::getType));
        for (Map.Entry<String, List<FundInfo>> entry : collect.entrySet()) {
            System.out.println(entry.getKey() + "    " + entry.getValue().size());
        }


        List<FundInfo> names = list.stream().filter(item -> {
            String type = item.getType();
            return (type.equals("混合型-灵活") || type.equals("混合-绝对收益") || type.equals("混合-绝对收益") || type.equals("混合型-偏股")
                    || type.equals("股票型") || type.equals("混合型-平衡"));

        }).collect(Collectors.toList());

        System.out.println("total funds is " + names.size());
        return names;

    }

    public String getFundNamesInCSV() {
        List<FundInfo> names = this.getFundNames();
        //找 2-50 亿的基金
        StringBuilder sb = new StringBuilder();
        names.stream().sorted(Comparator.comparing(FundInfo::getCode)).forEach(item -> {
            sb.append(item.getCode()).append(",").append(item.getName()).append(",").append(item.getType()).append("\n");
        });
        return sb.toString();
    }






    double getDouble(JSONObject fundObj, String key) {
        try {
            return fundObj.getDouble(key);
        } catch (Exception e) {
            return 0;
        }
    }

//    public Map<String, String> getOldFunds() {
//        List<FundInfo> trash = new ArrayList<>();
//
//        LocalDate today = LocalDate.now();
//
//        List<String> valueList = getValues("fund-profiles");
//        //filter trash
//        valueList.stream().map(item -> {
//            String json = (String) item;
//            FundInfo fundProfile = JSON.parseObject(json, FundInfo.class);
//            return fundProfile;
//        }).filter(fundProfile -> {
//            if (fundProfile == null) {
//                return false;
//            }
//            return fundProfile.getScale() == 0 || fundProfile.getType().equals("指数型") || fundProfile.getType().equals("债券型");
//        }).forEach(fundProfile -> {
//            redisTemplate.opsForHash().delete("fund-profiles", fundProfile.getCode());
//            System.out.println("delete fund " + fundProfile.getName() + "  " + fundProfile.getCode() + "  " + fundProfile.getScale());
//        });
//
//
//        Map<String, String> collect = valueList.stream().map(item -> {
//            String json = (String) item;
//            FundInfo fundProfile = JSON.parseObject(json, FundInfo.class);
//            return fundProfile;
//        }).filter(fundProfile -> {
//            if (fundProfile == null) {
//                return false;
//            }
//            if (fundProfile.getUpdateDate() == null) {
//                return true;
//            }
//            if (fundProfile.getUpdateDate().compareTo(today) < 0) {
//                return true;
//            }
//            return false;
//        }).collect(Collectors.toMap(FundInfo::getCode, FundInfo::getName));
//        System.out.println("old funds number is " + collect.size());
//        return collect;
//    }


    public String getFundProfile(String code) {
        try {
            String fund = restTemplate.getForObject(propertyConfig.getStockService() + "/data/fund/profile/" + code, String.class);
            return fund;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public String getFundDetail(String code) {
        try {
            String fund = restTemplate.getForObject(propertyConfig.getStockService() + "/data/fund/detail/" + code, String.class);
            return fund;
        } catch (Exception e) {
            logger.error(code);
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    //基金每日價格
    public void storeFundDetail(String code, String content) {
        try {
            restTemplate.postForObject(propertyConfig.getStockService() + "/fund/detail/" + code, content, String.class);
        } catch (Exception e) {
            logger.error(code);
            logger.error(e.getMessage(), e);
        }

    }

    //財報信息和總體信息
    public void storeFundProfile(String code, String content) {
        try {
            restTemplate.postForObject(propertyConfig.getStockService() + "/fund/profile/" + code, content, String.class);
        } catch (Exception e) {
            logger.error(code);
            logger.error(e.getMessage(), e);
        }
    }


}
